<template>
    <div class="pagestyle">
        <div class="queryBox">
            <el-form :model="state.form" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="报表选择">
                            <el-select class="w100" v-model="state.form.pumpReportName" @change="pumpReportNameChange"
                                placeholder="请选择">
                                <el-option v-for="item in state.attainAllPumpReportList" :label="item.pumpReportName"
                                    :value="item.pumpReportName" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报表时间">
                            <el-date-picker class="w100" v-if="state.form.type=='H'||state.form.type=='D'"
                                v-model="state.form.time" type="date" placeholder="请选择" @change="timeChange" />
                            <el-date-picker class="w100" @change="timeChange" v-if="state.form.type=='M'"
                                v-model="state.form.time" type="month" placeholder="请选择" />
                            <el-date-picker class="w100" @change="timeChange" v-if="state.form.type=='Y'"
                                v-model="state.form.time" type="year" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="显示当前抽采点">
                            <el-switch @change="isShowLocalPointChange" v-model="state.form.isShowLocalPoint" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="抽采点">
                            <el-select class="w100" :multiple="state.form.isShowDetail?false:true"
                                v-model="state.form.pumpNamecha" placeholder="请选择">
                                <el-option v-for="item in state.pumpNameList" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3" v-if="state.form.label=='PMR'">
                        <el-form-item label="是否分旬展示">
                            <el-switch v-model="state.form.isSeparationShow" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="显示一氧化碳">
                            <el-switch v-model="state.form.yiyangShow" @change="yiyangChange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="显示合计信息">
                            <el-switch :disabled="state.form.isShowDetail" v-model="state.form.isAggregation" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="是否显示详情" v-if="state.form.label!='MPD'&&state.form.label!='MPM'">
                            <el-switch :disabled="state.form.isAggregation||state.form.isSeparationShow"
                                @change="isShowDetailChange" v-model="state.form.isShowDetail" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item>
                            <el-button type="info" @click="queryBtnClick(0)">重置</el-button>
                            <el-button type="primary" @click="queryBtnClick(1)">查询</el-button>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
        </div>
        <div class="tableBox" style="height: 600px;">
            <p>
                <span class="title">报表</span>
                <span style="display: flex;">
                    <span class="listInfoBtn" @click="settingBtnClick(1)">
                        <svg-icon class-name="search-icon" icon-class="shezhi-geejkf58" />打印</span>

                    <span class="listInfoBtn" @click="settingBtnClick(2)" ref="listInfoBtn">
                        <svg-icon class-name="search-icon" icon-class="shezhi-geejkf58" />标题签名设置</span>
                </span>
            </p>
            <vxe-grid v-if="state.theadesNew.length>1&&!state.form.isSeparationShow" ref="xGrid" v-bind="{
              height:'560',
          columns:[{ field: 'seq', type: 'seq', width: 60 }].concat(state.theadesNew),
          data:state.tableData,
          align: 'center',
          showFooter:state.form.isAggregation? true:false,
       footerData: [
    {
  seq: '合计',
  samplePointName: '-',
  samplePointLocation: '-',
  extractionDataTime: '-',
  extractionGasValue: '-',
  extractionPressureValue:'-',
  extractionTempValue:'-',
  extractionCoValue:'-',
  conditionAvgMixedFlow:'-',
  conditionAvgPureFlow:'-',
  conditionMixedFlow:sumNum('conditionMixedFlow'),
  conditionPureFlow:sumNum('conditionPureFlow'),
  stpStMixedFlow:'-',
  stpStPureFlow:'-',
  stpAvgStMixedFlow:sumNum('stpAvgStMixedFlow'),
  stpAvgStPureFlow:sumNum('stpAvgStPureFlow')
}
  ]
        }"></vxe-grid>
            <div v-else-if="state.form.isSeparationShow" ref="printArea">
                <p v-if="state.tableDatas.length>0" style="text-align: center;font-size: 16px;font-weight: 700;width: 100%;display: flex;
                    justify-content: center;">上旬</p>
                <div v-if="state.tableDatas.length>0" style="text-align: right;font-size: 14px;">
                    时间范围:{{ dayjs(state.form.time).format('YYYY-MM-01 00:00:00') }}~{{ dayjs(state.form.time).format('YYYY-MM-10 23:59:59') }}
                </div>
                <vxe-grid ref="xGrid" v-if="state.tableDatas.length>0" v-bind="{
              height:'150',
          columns:[{ field: 'seq', type: 'seq', width: 60 }].concat(state.theadesNew),
          data:state.tableDatas,
          align: 'center',
          showFooter:state.form.isAggregation? true:false,
       footerData: [
    {
  seq: '合计',
  samplePointName: '-',
  samplePointLocation: '-',
  extractionDataTime: '-',
  extractionGasValue: '-',
  extractionPressureValue:'-',
  extractionTempValue:'-',
  extractionCoValue:'-',
  conditionAvgMixedFlow:'-',
  conditionAvgPureFlow:'-',
  conditionMixedFlow:sumNum('conditionMixedFlow'),
  conditionPureFlow:sumNum('conditionPureFlow'),
  stpStMixedFlow:'-',
  stpStPureFlow:'-',
  stpAvgStMixedFlow:sumNum('stpAvgStMixedFlow'),
  stpAvgStPureFlow:sumNum('stpAvgStPureFlow')
}
  ]
        }"></vxe-grid>
                <p v-if="state.tableDataz.length>0" style="text-align: center;font-size: 16px;font-weight: 700;width: 100%;display: flex;
                    justify-content: center;">中旬</p>
                <div v-if="state.tableDataz.length>0" style="text-align: right;font-size: 14px;">
                    时间范围:{{ dayjs(state.form.time).format('YYYY-MM-11 00:00:00') }}~{{ dayjs(state.form.time).format('YYYY-MM-20 23:59:59') }}
                </div>
                <vxe-grid v-if="state.tableDataz.length>0" ref="xGrid" v-bind="{
              height:'150',
          border:'inner',
          columns:[{ field: 'seq', type: 'seq', width: 60 }].concat(state.theadesNew),
          data:state.tableDataz,
          align: 'center',
          showFooter:state.form.isAggregation? true:false,
       footerData: [
    {
  seq: '合计',
  samplePointName: '-',
  samplePointLocation: '-',
  extractionDataTime: '-',
  extractionGasValue: '-',
  extractionPressureValue:'-',
  extractionTempValue:'-',
  extractionCoValue:'-',
  conditionAvgMixedFlow:'-',
  conditionAvgPureFlow:'-',
  conditionMixedFlow:sumNum('conditionMixedFlow'),
  conditionPureFlow:sumNum('conditionPureFlow'),
  stpStMixedFlow:'-',
  stpStPureFlow:'-',
  stpAvgStMixedFlow:sumNum('stpAvgStMixedFlow'),
  stpAvgStPureFlow:sumNum('stpAvgStPureFlow')
}
  ]
        }"></vxe-grid>
                <p v-if="state.tableDatax.length>0" style="text-align: center;font-size: 16px;font-weight: 700;width: 100%;display: flex;
                    justify-content: center;">下旬</p>
                <div v-if="state.tableDatax.length>0" style="text-align: right;font-size: 14px;">
                    时间范围:{{ dayjs(state.form.time).format('YYYY-MM-21 00:00:00') }}~{{ dayjs(state.form.time).format(`YYYY-MM-${dayjs(state.form.time).endOf('month').date()} 23:59:59`) }}
                </div>
                <vxe-grid v-if="state.tableDatax.length>0" ref="xGrid" v-bind="{
              height:'150',
          border:'inner',
          columns:[{ field: 'seq', type: 'seq', width: 60 }].concat(state.theadesNew),
          data:state.tableDatax,
          align: 'center',
          showFooter:state.form.isAggregation? true:false,
       footerData: [
    {
  seq: '合计',
  samplePointName: '-',
  samplePointLocation: '-',
  extractionDataTime: '-',
  extractionGasValue: '-',
  extractionPressureValue:'-',
  extractionTempValue:'-',
  extractionCoValue:'-',
  conditionAvgMixedFlow:'-',
  conditionAvgPureFlow:'-',
  conditionMixedFlow:sumNum('conditionMixedFlow'),
  conditionPureFlow:sumNum('conditionPureFlow'),
  stpStMixedFlow:'-',
  stpStPureFlow:'-',
  stpAvgStMixedFlow:sumNum('stpAvgStMixedFlow'),
  stpAvgStPureFlow:sumNum('stpAvgStPureFlow')
}
  ]
        }"></vxe-grid>
            </div>
        </div>
        <!-- 报表设置 -->
        <div v-if="state.setModal" class="reportSetBox" :style="{position: 'absolute',left:state.xydata.x+'px',
                top:state.xydata.y+'px',zIndex:100}">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="标题内容">
                            <el-input v-model="state.formData.titleName">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="标题字体">
                            <el-select class="w100" v-model="state.formData.titleTypeface" clearable placeholder="请选择">
                                <el-option v-for="itemsub in ['微软雅黑']" :key="itemsub" :label="itemsub" :value="itemsub">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="显示签名栏边框">
                            <el-switch v-model="state.formData.showBorder">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="显示打印人员">
                            <el-switch v-model="state.formData.showPersonnel">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="显示原因分析">
                            <el-switch v-model="state.formData.showReason">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-for="(item,index) in ['One','Two','Three','Four','Five','Six']">
                        <el-form-item :label="'标名'+(index+1)">
                            <el-select class="w100" v-model="state.formData['title'+item]" clearable placeholder="请选择">
                                <el-option v-for="itemsub in ['无','矿长','总工','队长']" :key="itemsub" :label="itemsub"
                                    :value="itemsub">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" style="text-align: right;margin-top: 10px;">
                        <el-button type="info" @click="cancelClick">取消</el-button>
                        <el-button type="primary" @click="settingClick">确定</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>
<script setup>
    import {
        computed,
        nextTick,
        onMounted,
        reactive
    } from "vue";
    import {
        table_headers
    } from "@/components/commonCom/table_headers";
    import axios from "@/utils/request";
    import usePagesStore from "@/store/modules/pages";
    import {
        ElMessage,
        ElMessageBox
    } from "element-plus";
    import dayjs from 'dayjs'
    const {
        proxy
    } = getCurrentInstance();
    const store = usePagesStore();
    const router = useRouter();
    let state = reactive({
        theadesNew: [],
        xydata: {
            x: 0,
            y: 0
        },
        tableData: [],
        tableDatas: [],
        tableDataz: [],
        tableDatax: [],
        options: {
            ismergethead: [{
                value: 'condition',
                label: '工况'
            }, {
                value: 'stp',
                label: '标况'
            }],
            tableheads: computed(() => table_headers.hisGasPumpHour),
            queryList: {
                dropdownUrl: "",
                querys: [],
                queryMap: new Map([]),
            },
            dataUrl: "/freeReportTemplate/attainPumpHourInfo",
        },
        modalTitle: '抽采利用新增',
        addModal: false,
        open_detail: false,
        descList1: [],
        form: {
            isShowLocalPoint: false,
            isSeparationShow: false,
            yiyangShow: true,
            isAggregation: false,
            isShowDetail: false,
            type: 'H'
        },
        attainAllPumpReportList: [],
        pumpNameList: [],
        formData: {},
        rules: {},
        setModal: false

    });
    const sumNum = (field) => {
        let count = 0
        state.tableData.forEach(item => {
            count += Number(item[field])
        })
        return count.toFixed(2)
    }

    function timeChange(val) {
        let endVal = dayjs(state.form.time).endOf('month').date()
        if (state.form.type == 'H') {
            state.form.startTime = dayjs(state.form.time).format('YYYY-MM-DD 00:00:00')
            state.form.endTime = dayjs(state.form.time).format('YYYY-MM-DD 23:59:59')
        } else if (state.form.type == 'D') {
            state.form.startTime = dayjs(state.form.time).format('YYYY-MM-DD 00:00:00')
            state.form.endTime = dayjs(state.form.time).format('YYYY-MM-DD 23:59:59')
        } else if (state.form.type == 'M') {
            state.form.startTime = dayjs(state.form.time).format('YYYY-MM-01 00:00:00')
            state.form.endTime = dayjs(state.form.time).format(`YYYY-MM-${endVal} 23:59:59`)
        } else if (state.form.type == 'Y') {
            state.form.startTime = dayjs(state.form.time).format('YYYY-01-01 00:00:00')
            state.form.endTime = dayjs(state.form.time).format(`YYYY-12-31 23:59:59`)
        }
        getattainExtractionPoint()
    }
    // 获取逻辑对象名称
    const getattainAllPumpReport = () => {
        axios.get('/freeReportTemplate/attainAllPumpReport').then(res => {
            state.attainAllPumpReportList = res.data
            state.form.pumpReportName = res.data[0].pumpReportName
            state.form.label = res.data[0].label
            state.form.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
            state.form.startTime = dayjs(state.form.time).format('YYYY-MM-DD 00:00:00')
            state.form.endTime = dayjs(state.form.time).format('YYYY-MM-DD 23:59:59')
            getattainExtractionPoint()
        })
    }
    const getattainExtractionPoint = () => {
        axios.post('/freeReportTemplate/attainExtractionPoint', {
            startTime: state.form.startTime,
            endTime: state.form.endTime,
            isShowLocalPoint: state.form.isShowLocalPoint
        }).then(res => {
            state.pumpNameList = res.data
        })
    }
    // 显示当前抽采点
    function isShowLocalPointChange(val) {
        state.form.pumpNamecha = []
        getattainExtractionPoint()
    }

    function isShowDetailChange() {
        state.form.pumpNamecha = []
    }

    function pumpReportNameChange(val) {
        state.form.pumpNamecha = []
        state.theadesNew = []
        state.form.isSeparationShow = false
        state.form.yiyangShow = true
        state.form.isShowDetail = false
        state.form.isShowDetail = false
        state.attainAllPumpReportList.forEach(item => {
            if (val == item.pumpReportName) {
                state.form.pumpReportName = item.pumpReportName
                state.form.label = item.label
                state.form.type = item.type
                let endVal = dayjs().endOf('month').date()
                if (item.type == 'H') {
                    state.form.startTime = dayjs(state.form.time).format('YYYY-MM-DD 00:00:00')
                    state.form.endTime = dayjs(state.form.time).format('YYYY-MM-DD 23:59:59')
                } else if (item.type == 'D') {
                    state.form.startTime = dayjs(state.form.time).format('YYYY-MM-DD 00:00:00')
                    state.form.endTime = dayjs(state.form.time).format('YYYY-MM-DD 23:59:59')
                } else if (item.type == 'M') {
                    state.form.startTime = dayjs(state.form.time).format('YYYY-MM-01 00:00:00')
                    state.form.endTime = dayjs(state.form.time).format(`YYYY-MM-${endVal} 23:59:59`)
                } else if (item.type == 'Y') {
                    state.form.startTime = dayjs(state.form.time).format('YYYY-01-01 00:00:00')
                    state.form.endTime = dayjs(state.form.time).format(`YYYY-12-31 23:59:59`)
                }
                getattainExtractionPoint()
            }
        })
    }
    let newthead1 = computed(() => table_headers.hisGasPumpHour)
    let newthead = ref([])
    newthead1.value.forEach(item => {
        if (item.field != 'orderId' && item.field != 'remark') {
            newthead.value.push(item)
        }
    })
    let newarr = ref([])
    state.theadesNew = classifyArrays(newthead, state.options.ismergethead, 'field')

    function yiyangChange(val) {
        if (!val) {
            newarr.value = []
            newthead.value.forEach(item => {
                if (item.field != 'extractionCoValue') {
                    newarr.value.push(item)
                }
            })
            state.theadesNew = classifyArrays(newarr, state.options.ismergethead, 'field')
        } else {
            state.theadesNew = classifyArrays(newthead, state.options.ismergethead, 'field')
        }
    }

    function getList() {
        console.log(state.form.pumpNamecha, "state.form.pumpNamecha")
        state.form.pumpName = Array.isArray(state.form.pumpNamecha) && state.form.pumpNamecha.length > 0 ?
            state.form.pumpNamecha.join(';') : state.form.pumpNamecha
        if (state.pumpNameList.length == 0) {
            ElMessage.warning('抽采点暂无数据,无法进行查询!')
        } else if (state.form.pumpReportName.includes('多测点') && state.form.pumpNamecha.length < 2) {
            ElMessage.warning('多测点下抽采点必须选择两个以上!')
        } else if (state.form.pumpNamecha && state.form.pumpNamecha.length == 0) {
            proxy.$modal.msgWarning('请选择抽采点');
        } else {
            axios.post('/freeReportTemplate/attainPumpHourInfo', state.form).then(res => {
                res.data.forEach(item => {
                    if (item.flag == 'U') {
                        state.tableDatas.push(item)
                    } else if (item.flag == 'M') {
                        state.tableDataz.push(item)
                    } else if (item.flag == 'D') {
                        state.tableDatax.push(item)
                    }
                })
                state.tableData = res.data
            }).catch(err => {
                state.tableData = []
            })
        }
    }

    function queryBtnClick(type) {
        if (state.form.pumpReportName && state.form.pumpReportName.includes('多测点')) {
            state.options.ismergethead = [{
                    value: 'extraction',
                    label: '抽采参数'
                },
                {
                    value: 'condition',
                    label: '工况'
                }, {
                    value: 'stp',
                    label: '标况'
                }
            ]
        } else {
            state.options.ismergethead = [{
                value: 'condition',
                label: '工况'
            }, {
                value: 'stp',
                label: '标况'
            }]
        }
        if (type == 0) {
            state.form.pumpReportName = state.attainAllPumpReportList[0].pumpReportName
            state.form.time = dayjs().format('YYYY-MM-DD HH:mm:ss')

        } else if (type == 1) {
            nextTick(() => {
                state.theadesNew = classifyArrays(newthead, state.options.ismergethead, 'field')
            })
        }
        getList()

    }

    function settingClick() {
        state.formData.itemName = state.form.pumpReportName
        axios.post('/fixReport/addFixReport', state.formData).then(res => {
            proxy.$modal.msgSuccess(res.msg);
            state.setModal = false
        })
    }

    function cancelClick() {
        state.setModal = false
    }

    function settingBtnClick(type) {
        if (type == 1) {
            if (state.form.isSeparationShow) {
                let $printArea = proxy.$refs.printArea
                if ($printArea) {
                    const html = $printArea.innerHTML;
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
          <head>
            <style>
              @page { size: auto; margin: 0; }
              body { margin: 5mm; }
              table { width: 100%; border-collapse: collapse; }
              .vxe-table--empty-block{
                display:none;
              }
              vxe-header--row,
              .vxe-body--row{
                border:1px solid #ddd;
              }
              .vxe-header--row,
              .vxe-body--column{
                border:1px solid #ddd;
              }

              .vxe-body--y-space{
                display:none;
              }
              .vxe-cell{
                width: auto !important;
                height: auto !important;
                padding: 10px;
              }
              .vxe-cell--title,
              .vxe-cell--label{
                white-space: nowrap;
              }
              .vxe-table--scroll-y-virtual,
              .vxe-table--empty-placeholder{
display:none;
                
              }
              .vxe-table--body,
              .vxe-table--header{
                width:100% !important;

              }
                 .header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 50px;
        background: white;
        padding: 5mm;
      }
         /* 固定页脚样式 */
      .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 40px;
        background: white;
        padding: 5mm;
        text-align: center;
      }
      
            </style>
          </head>
          <body>
            <div style="text-align: center;">
                ${state.form.pumpReportName}
                </div>
                 <div class="content">
                ${html}
                </div>
                <div class="footer">表尾</div>
                </body>
        </html>
      `);
                    printWindow.document.close();
                    printWindow.print();
                }
            } else {
                const $table = proxy.$refs['xGrid']
                if ($table) {
                    $table.print()
                }
            }
        } else
        if (type == 2) {
            state.formData.titleName = state.form.pumpReportName
            state.xydata.x = proxy.$refs['listInfoBtn'].offsetLeft - 400
            state.xydata.y = proxy.$refs['listInfoBtn'].offsetTop + 40
            state.setModal = true
        }
    }



    function classifyArrays(mainArray, filterArray, fieldName) {
        const tree = [];
        const containsValues = [];
        const notContainsValues = [];
        filterArray.forEach(category => {
            const node = {
                field: category.value,
                children: []
            };
            // 筛选属于当前分类的数据项
            const itemsInCategory = mainArray.value.filter(item => (item.field).includes(category.value));
            node.name = itemsInCategory.length > 0 && itemsInCategory[0].name
            node.title = category.label
            node.children = itemsInCategory;
            // 将节点添加到树中
            tree.push(node);
        });
        mainArray.value.forEach(item => {
            const fieldValue = item[fieldName];
            const isContained = filterArray.some(filterValue => {
                return fieldValue.includes(filterValue.value);
            });
            if (isContained) {
                containsValues.push(item);
            } else {
                notContainsValues.push(item);
            }
        });
        let newdata = notContainsValues.concat(tree)
        console.log(newdata, "大萨达几哈")
        return newdata
    }


    onMounted(() => {
        getattainAllPumpReport()
    })
</script>
<style lang="scss" scoped>
    .reportSetBox {
        padding: 12px;
        max-width: 596px;
        min-width: 400px;
        border-radius: 8px;
        background: rgba(255, 255, 255, 0.8);
        box-shadow: 0px 2px 20px rgba(91, 109, 128, 0.2);
        backdrop-filter: blur(20px);
    }

    .tableBox,
    .queryBox {
        margin-bottom: 10px;
        background-color: rgba(255, 255, 255, 0.4);
        border-radius: 4px;
        padding: 16px;

        p {
            margin: 0 0 10px 0;
            padding: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

    }
</style>